package jmine.tec.subscription.impl;

import java.util.concurrent.TimeUnit;

import jmine.tec.cache.ExpiringMap;
import jmine.tec.subscription.Publication;
import jmine.tec.subscription.PublicationStore;
import jmine.tec.subscription.SubscriptionSettings;

/**
 * Implementacao padrao de {@link PublicationStore} que 'expira'
 * 
 * @author takeshi
 * @param <P> o tipo da {@link Publication}
 */
public class ExpiringPublicationStore<P extends Publication> implements PublicationStore<P> {

    private final ExpiringMap<SubscriptionSettings, P> map = new ExpiringMap<SubscriptionSettings, P>(true, 600, TimeUnit.SECONDS);

    /**
     * {@inheritDoc}
     */
    public void evict(SubscriptionSettings settings) {
        this.map.remove(settings);
    }

    /**
     * {@inheritDoc}
     */
    public P lastPublication(SubscriptionSettings settings) {
        return this.map.get(settings);
    }

    /**
     * {@inheritDoc}
     */
    public boolean update(SubscriptionSettings settings, P publication) {
        P p = this.map.get(settings);
        if (p == null || publication.isNewerThan(p)) {
            this.map.put(settings, publication);
            return true;
        }
        return false;
    }

    /**
     * Apaga o cache inteiro
     */
    public void evictAll() {
        this.map.clear();
    }

    /**
     * @return int
     */
    public int getEntries() {
        return this.map.size();
    }

}
